package com.woniuxy.charin.aspect;
import com.woniuxy.charin.cache.AuthCache;
import com.woniuxy.charin.common.ann.AuthAnnotation;
import com.woniuxy.charin.enumeration.BusinessCode;
import com.woniuxy.charin.util.JwtUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.woniuxy.charin.enumeration.Assert;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Component
@Aspect
public class AuthAspect {
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    AuthCache authCache;
    @Pointcut(value = "@annotation(authAnnotation)")
    public void myPointcut(AuthAnnotation authAnnotation){}

    @Before(value = "myPointcut(authAnnotation)")
    public void checkPermission(JoinPoint joinPoint,AuthAnnotation authAnnotation){
        String code = authAnnotation.value();
        ServletRequestAttributes srAttr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = srAttr.getRequest();
        String authorization = request.getHeader("authorization");

      Integer userId = Integer.valueOf((jwtUtil.getValue(authorization, "userId")));
        Set<String> userPermissions = authCache.getPermissionsByUser(userId);
        Assert.error(!userPermissions.contains(code), BusinessCode.NO_PERMISSION);

    }


}
